/*
 * Copyright The OpenTelemetry Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package com.xiashitech.agent.instrumentation.redis.redisson;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.instrumentation.redis.RedisData;
import com.xiashitech.agent.instrumentation.redis.constants.CommandNames;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.SessionUtil;
import io.opentelemetry.javaagent.shaded.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;

import java.util.function.BiFunction;


public final class XSEndOperationListener<T> implements BiFunction<T,Throwable,RedisData> {
    private final Instrumenter<RedisData, RedisData> instrumenter;
    private final Context context;
    private final RedisData redisData;

    public XSEndOperationListener(Instrumenter<RedisData, RedisData> instrumenter, Context context, RedisData redisData) {
        this.instrumenter = instrumenter;
        this.context = context;
        this.redisData = redisData;
    }


    @Override
    public RedisData apply(T result, Throwable error) {
        try {
            if (CommandNames.GET.getName().equals(redisData.getRedisOpetion())) {
                redisData.setValue(SessionUtil.convertObjectToByteArray(result));
            }
            instrumenter.end(context, redisData, redisData, error);
            redisData.getRedissonRequest().setBaggage(BaggageUtil.mergeBaggageFromContext(Baggage.current(),context).build());
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return redisData;
    }
}
